import axios from 'axios';
import VueCookie from 'vue-cookie';
import apiConfig from './api.config';

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = apiConfig.baseUrl; // 配置接口地址，判断是线上还是调试

let path = [28, 246].includes(apiConfig.serverNum) ? 'Home' : 'Qdmes/QDMES';
function send (csname, listStr, DATABASENAME, isGet = true, isSap = false, isPDA = false) {
    return new Promise((resolve, reject) => {
        if (!(listStr instanceof Array)) {
            listStr = listStr.replace(/null/g, '').replace(/undefined/g, '');
            // 正常例子:let param = `14602🈹这里是备注🈹2025/07/24` 
            // 没有\t直接把🈹替换成\t 就行
            // 错误例子:let param = `14602🈹这里是备注\t🈹2025/07/24` 
            // 备注内容藏了一个\t, 直接调会报错: 条件参数不一致,所以先把所有\t替换成空格再把🈹替换成\t
            listStr = listStr.replace(/\t/g, ' ').replace(/🈹/g, '\t');
        }
        //处理图片路径
        let params = {
            csname,
            listStr,
            DATABASENAME
        };
        if (isSap) {
            var sap = {};
            sap.csname = csname;
            //如果有表格传入,listStr的格式为
            // [{ name: 'param', listStr: '字符串参数' },
            // { name: '表名1', arr: [] },
            // { name: '表名2', arr: [] }];
            if (listStr instanceof Array) {

                //转成sap接口能读的表
                let json2commitJsonTab = function (tableName, json, columnNames) {
                    var tab = {};
                    tab.N = tableName;
                    tab.RS = [];
                    if (columnNames == "") {
                        columnNames = [];
                        for (j in json[0]) {

                            columnNames.push(j);
                        }
                    }
                    for (var i = 0; i < json.length; i++) {
                        var R = {};
                        R.I = i;
                        R.CS = [];
                        for (var j = 0; j < columnNames.length; j++) {
                            var n = columnNames[j];
                            var C = {};
                            C.N = n;
                            C.V = json[i][n];
                            R.CS.push(C);
                        }

                        tab.RS.push(R);
                    }
                    return tab;
                };

                //字符串参数parmastr
                sap.parmastr = listStr.find(item => item.name == 'param')['listStr'].replace(/\t/g, "<&nbst>");
                //表格参数tabJson
                let tabJson = [];
                for (let i = 0; i < listStr.length; i++) {
                    let item = listStr[i];
                    if (item.name == 'param') {
                        continue;
                    }
                    else {
                        let tab = json2commitJsonTab(item.name, item.arr, "");
                        tabJson.push(tab);
                    }
                }
                tabJson = JSON.stringify(tabJson);
                sap.tabJson = tabJson;
            }
            else {
                sap.parmastr = listStr.replace(/\t/g, "<&nbst>");
                sap.tabJson = '';
            }
            sap.asdno = DATABASENAME;
            sap.company = 'QD';
            sap = JSON.stringify(sap);
            axios({
                url: `./${path}/RunMethodByNamePDA`,
                method: 'post',
                data: { MethodName: 'GetDataFromSap6', parameters: sap, returnType: 'string' },
                dataType: "text",
            }).then((response) => {
                resolve(response.data);
            }).catch(err => {
                console.log('err :>> ', err);
                reject(err);
            });


            // for (var i = 0; i < selectRows.length; i++) {
            //     saptab.push({
            //         VBELN: selectRows[i].VBELN,
            //         POSNR: selectRows[i].POSNR,
            //         SERNR: selectRows[i].SERNR,
            //         DY2: dy2,
            //         DB2: db2,
            //         D3: d3,
            //         DY3: dy3,
            //         DB3: db3,
            //         D4: d4,
            //         DY4: dy4,
            //         DB4: db4,
            //         D5: d5,
            //         DY5: dy5,
            //         DB5: db5,
            //     });
            // }

            // var tabJson = [];
            // var tab = json2commitJsonTab("IN_PROSN", saptab, "");
            // tabJson.push(tab);
            // tabJson = JSON.stringify(tabJson);
            // var sap = {};
            // sap.csname = "SAP查询智联应收款数据",
            //     sap.parmastr = 'W4<&nbst><&nbst><&nbst><&nbst><&nbst><&nbst><&nbst>';
            // sap.tabJson = tabJson;
            // sap.asdno = "9911";
            // sap.company = "ZL";
            // sap = JSON.stringify(sap);

            // myRunMethodByNamePDA(urlStr, "GetDataFromSap6", sap, "string", function (data) {
            //     data = $.parseJSON(data).TableSet.IT_PROSN;
            //     for (var i = 0; i < selectRows.length; i++) {
            //         selectRows[i].DY2 = data[0].DY2;
            //         selectRows[i].DY3 = data[0].DY3;
            //         selectRows[i].DY4 = data[0].DY4;
            //         selectRows[i].DY5 = data[0].DY5;
            //         selectRows[i].DB2 = data[0].DB2.replace('0000-00-00', '');
            //         selectRows[i].DB3 = data[0].DB3.replace('0000-00-00', '');
            //         selectRows[i].DB4 = data[0].DB4.replace('0000-00-00', '');
            //         selectRows[i].DB5 = data[0].DB5.replace('0000-00-00', '');
            //         selectRows[i].D3 = data[0].D3.replace('0000-00-00', '');
            //         selectRows[i].D4 = data[0].D4.replace('0000-00-00', '');
            //         selectRows[i].D5 = data[0].D5.replace('0000-00-00', '');
            //     }
            //     updateRows("tab_detail", selectRows);
            //     $('#dd_pl1').dialog('close');
            // });
        }
        else if (isPDA) {
            axios({
                url: `./${path}/RunMethodByNamePDA`,
                method: 'post',
                data: { MethodName: csname, parameters: listStr, returnType: 'string' },
                dataType: "text",
            }).then((response) => {
                console.log('response :>> ', response);
                resolve(response.data);
            }).catch(err => {
                console.log('err :>> ', err);
                reject(err);
            });
        }
        else {
            axios({
                url: `./${path}/${isGet ? 'GetDataTable_new' : 'commit_new'}`,
                method: isGet ? 'get' : 'post',
                params: isGet ? params : {},
                data: isGet ? {} : params,
                dataType: "text",
            }).then((response) => {
                if (response.data == 'reload') {
                    let ua = navigator.userAgent.toLowerCase();
                    let isWxWork = ua.indexOf('wxwork') > 0;

                    let currentUrl = window.location.href;
                    VueCookie.set('oldUrl', currentUrl);
                    //是否企业微信

                    if (isWxWork) {
                        if (apiConfig.serverNum == 28) {
                            window.location.href = apiConfig.baseUrl + '/MES/WXLogin_smart1.html?readNameAgain';
                        }
                        else if (apiConfig.serverNum == 30) {
                            window.location.href = apiConfig.baseUrl + '/QDMES/MES/WXLogin.html?readNameAgain';
                        }
                        else if (apiConfig.serverNum == 246) {
                            window.location.href = apiConfig.baseUrl + '/MES/WXLogin_smart1.html?readNameAgain';
                        }
                        else if (apiConfig.serverNum == 193) {
                            window.location.href = apiConfig.baseUrl + '/QDMES/MES/WXLogin.html?readNameAgain';
                        }
                    }
                    else {
                        if (apiConfig.serverNum == 28) {
                            window.location.href = apiConfig.baseUrl + '/MES/WXLogin_smart1.html?readNameAgain';
                        }
                        else if (apiConfig.serverNum == 30) {
                            window.location.href = apiConfig.baseUrl + '/QDMES/MES/Login.html';
                        }
                        else if (apiConfig.serverNum == 246) {
                            window.location.href = apiConfig.baseUrl + '/MES/SmartSolutionLogin.html';
                        }
                        else if (apiConfig.serverNum == 193) {
                            window.location.href = apiConfig.baseUrl + '/QDMES/MES/Login.html';
                        }
                    }
                }
                else {
                    resolve(response.data);
                }
            }).catch(err => {
                console.log('err :>> ', err);
                reject(err);
            });
        }
    });
}

let default_DATABASENAME = 'Q902';
const myAxios = {
    get (csname, listStr, DATABASENAME) {
        listStr = listStr ? listStr : '';
        DATABASENAME = DATABASENAME ? DATABASENAME : default_DATABASENAME;
        return send(csname, listStr, DATABASENAME);
    },
    post (csname, listStr, DATABASENAME) {
        listStr = listStr ? listStr : '';
        DATABASENAME = DATABASENAME ? DATABASENAME : default_DATABASENAME;
        return send(csname, listStr, DATABASENAME, false);
    },
    getSap (csname, listStr, DATABASENAME) {
        listStr = listStr ? listStr : '';
        DATABASENAME = DATABASENAME ? DATABASENAME : default_DATABASENAME;
        return send(csname, listStr, DATABASENAME, true, true);
    },
    getPDA (methodName, listStr) {
        listStr = listStr ? listStr : '';
        return send(methodName, listStr, '', true, false, true);
    },
    postToWeChat (empCode, title, description, url, isZL) {
        return new Promise((resolve, reject) => {
            //服务器为246默认推送智联DS
            let tokenname = apiConfig.serverNum == 246 ? 'ACCESS_TOKEN_ZL' : 'ACCESS_TOKEN';
            //如果有用户传值则按照用户传值
            if (isZL != undefined)
                tokenname = isZL ? 'ACCESS_TOKEN_ZL' : 'ACCESS_TOKEN';
            //多个工号用 | 隔开
            axios.get(`/${path}/WxWorkSendTextcard`, {
                params: {
                    empCode,
                    title,
                    description,
                    url,//默认推送外网地址
                    // url: `${apiConfig.baseUrl}/QDMES/ExamWeb/index.html#/Exam`,
                    btntxt: '点击进入',
                    tokenname,
                },
            }).then(() => {
                resolve(0);
                console.log('推送成功');
            }).catch((error) => {
                console.log('推送error :>> ', error);
                reject(-1);
            });
        });
    },
    postToWeChatText (empCode, title, message, isZL) {
        return new Promise((resolve, reject) => {
            //服务器为246默认推送智联DS
            let tokenname = apiConfig.serverNum == 246 ? 'ACCESS_TOKEN_ZL' : 'ACCESS_TOKEN';
            //如果有用户传值则按照用户传值
            if (isZL != undefined)
                tokenname = isZL ? 'ACCESS_TOKEN_ZL' : 'ACCESS_TOKEN';
            //多个工号用 | 隔开
            axios.get(`/${path}/WxWorkSendText`, {
                params: {
                    empCode,
                    title,
                    message,
                    // url,//默认推送外网地址
                    // url: `${apiConfig.baseUrl}/QDMES/ExamWeb/index.html#/Exam`,
                    btntxt: '点击进入',
                    tokenname,
                },
            }).then(() => {
                resolve(0);
                console.log('推送成功');
            }).catch((error) => {
                console.log('推送error :>> ', error);
                reject(-1);
            });
        });
    },
    uploadFile (base64String, filePath, fileName) {

        //压缩图片
        let compress = function (base64String, w = 1000, quality = 0.8) {
            return new Promise((resolve, reject) => {

                let getMimeType = function (urlData) {
                    let arr = urlData.split(",");
                    let mime = arr[0].match(/:(.*?);/)[1];
                    // return mime.replace("image/", "");
                    return mime;
                };
                let newImage = new Image();
                let imgWidth, imgHeight;
                newImage.onload = function () {
                    imgWidth = newImage.width;
                    imgHeight = newImage.height;
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    if (Math.max(imgWidth, imgHeight) > w) {
                        if (imgWidth > imgHeight) {
                            canvas.width = w;
                            canvas.height = (w * imgHeight) / imgWidth;
                        } else {
                            canvas.height = w;
                            canvas.width = (w * imgWidth) / imgHeight;
                        }
                    } else {
                        canvas.width = imgWidth;
                        canvas.height = imgHeight;
                    }
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
                    let base64 = canvas.toDataURL(getMimeType(base64String), quality);

                    resolve(base64);
                };

                newImage.src = base64String;

            });
        };

        //上传压缩后的图片
        let uploadImgae = function (base64, filePath, fileName) {
            return new Promise((resolve, reject) => {
                axios({
                    url: `/${path}/mySaveFile`,
                    data: {
                        // filename: `${1}.jpeg`,
                        // filePath: `D:\\QDMES\\CHER\\driver_order_menu\\img\\menu\\`,
                        filename: fileName,
                        filePath: filePath,
                        base64: base64.substring(base64.indexOf(",") + 1, base64.length)
                    },
                    method: 'post',
                }).then((res) => {
                    resolve(res.data);
                }).catch((error) => {
                    console.log('error :>> ', error);
                });
            });
        };
        return new Promise(async (resolve, reject) => {
            // console.log('base64 :>> ');
            let base64 = await compress(base64String);
            let result = await uploadImgae(base64, filePath, fileName);
            resolve(result);
        });
    },
};
export default myAxios;
